﻿// Parts Copyright 2008 Newgrove Consultants Limited
// Modified By John Diss 
// From original work:
//
// Copyright 2006 - Ricardo Stuven (rstuven@gmail.com)
//
// This file is part of MsSqlSpatial.
// MsSqlSpatial is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// MsSqlSpatial is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public License
// along with MsSqlSpatial; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 

using System.Data.SqlTypes;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Geometries;
using GisSharpBlog.NetTopologySuite.LinearReferencing;
using Microsoft.SqlServer.Server;
using MsSqlSpatial;
using MsSqlCoordinate2D = NetTopologySuite.Coordinates.BufferedCoordinate;


public partial class UserDefinedFunctions
{
    /// <summary>
    /// PostGIS docs:
    /// 
    /// line_interpolate_point(linestring, location)
    /// 
    /// Returns a poin interpolated along a line. 
    /// 
    /// First argument must be a LINESTRING. 
    /// 
    /// Second argument is a float8 between 0 and 1 
    /// representing fraction of total 2d length the point has to be located. 
    /// 
    /// See line_locate_point() for computing the line location nearest to a Point. 
    /// 
    /// Note
    /// Since release 1.1.1 this function also interpolates M and Z values (when present), while prior releases set them to 0.0. 
    /// 
    /// </summary>
    /// <param name="ewkb"></param>
    /// <returns></returns>
    [SqlFunction(IsDeterministic = true)]
    public static SqlBytes LineInterpolatePoint(SqlBytes ewkb, SqlDouble location)
    {
        IGeometry geometry = ConvertGeometry.ToGeometry(ewkb);
        if (geometry is LineString<MsSqlCoordinate2D> && !location.IsNull)
        {
            var indexedLine = new LengthIndexedLine<MsSqlCoordinate2D>((IGeometry<MsSqlCoordinate2D>) geometry);
            double index = location.Value*GeometryUtilities.Length(geometry);
            return ConvertGeometry.ToSqlBytes(
                Global.Services.GeometryFactory.CreatePoint(indexedLine.ExtractPoint(index)),
                GeometryUtilities.MsSqlSpatialSrid(geometry));
        }
        return SqlBytes.Null;
    }
} ;